package com.ce.pms.authorization.tag;

import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.jstl.core.ConditionalTagSupport;

import com.ce.pms.authorization.filter.PmsAuthenticateFilter;
import com.ce.pms.authorization.model.AuthorizedInfo;
import com.ce.util.BlankUtil;
import com.ce.webframework.sec.util.InitPlugIn;

/**
 * 页面按钮权限控制标签
 *
 * @author  编写日期：2007年11月13日
 */
public class AuthTag extends ConditionalTagSupport  {

	private String authName;

	private String authType;

	private String returnType;

	/**
	 * 如果页面本标签内容不为空并且该页面按钮名称和权限系统定义的
	 * 按钮名称相同，那么页面将会显示该标签的内容，否则内容显示为空
	 */
	@Override
	protected boolean condition() throws JspTagException {
		// TODO Auto-generated method stub

			if (verifyButtonAuth(getAuthInfo(), authName,authType)) {
				return true;
			}else{
				return false;
			}

	}


	/**
	 * 把该按钮名称和权限系统的按钮名称进行比对，判断该用户是否拥
	 * 有该按钮权限
	 * @param authInfo 该用户权限信息
	 * @param buttonName 页面按钮名
	 */
	private boolean verifyButtonAuth(AuthorizedInfo authInfo,String authName,String authType) {
		if(BlankUtil.isBlank(authInfo))
			return false;
		if(BlankUtil.isBlank(authInfo.getButtonMap()))
			return false;
		Map allMap=(Map)this.pageContext.getServletContext().getAttribute(InitPlugIn.APPLICATION_ALL_AUTH);
		if(!allMap.containsKey(authName)){
			return true;
		}
        if(BlankUtil.isBlank(authType)){
		return authInfo.getButtonMap().containsValue(authName.trim());
        }else if("url".equalsIgnoreCase(authType)){
        	if(!BlankUtil.isBlank(returnType) && "false".equalsIgnoreCase(returnType)){
        	return !authInfo.getUrlMap().containsValue(authName.trim());
        	}else {
        		return authInfo.getUrlMap().containsValue(authName.trim());
        	}
        }else{
        	return authInfo.getButtonMap().containsValue(authName.trim());
        }
	}


	/**
	 * 获得权限系统的授权信息
	 */
	private AuthorizedInfo getAuthInfo() {
		HttpSession session=this.pageContext.getSession();
		AuthorizedInfo authInfo = (AuthorizedInfo) session.getAttribute(PmsAuthenticateFilter.LOGIN_USER_RIGHT_KEY);
		return authInfo;
	}

	public void setAuthName(String authName) {
		this.authName = authName;
	}
	public void setAuthType(String authType) {
		this.authType = authType;
	}
	public void setReturnType(String returnType) {
		this.returnType = returnType;
	}

}
